package com.micosco.taskremind.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import com.micosco.taskremind.R;
import com.micosco.taskremind.data.RemindType;
import com.micosco.taskremind.data.Task;
import com.micosco.taskremind.data.TaskDatabase;
import com.micosco.taskremind.data.TaskList;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 该Activity用于创建作业和修改作业信息
 */
public class TaskInfoActivity extends AppCompatActivity
        implements AdapterView.OnItemSelectedListener {
    RemindType selectedType;

    //TYPE extra值
    //启动用于创建新作业的Activity
    public static final int NEW_TASK = 0;
    //启动用于显示已有作业详细信息的Activity
    public static final int TASK_INFO = 1;

    private int activityType;

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_info);

        //设置Spinner of RemindType
        Spinner remindTypeSpinner = findViewById(R.id.remind_type_spinner);
        ArrayAdapter<RemindType> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, RemindType.ALL_TYPE);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        remindTypeSpinner.setAdapter(adapter);

        toolbar = findViewById(R.id.new_task_toolbar);
        setSupportActionBar(toolbar);

        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @SuppressLint("DefaultLocale")
    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = getIntent();
        activityType = intent.getIntExtra("TYPE", 0);
        switch (activityType) {
            case NEW_TASK:
                toolbar.setTitle(getString(R.string.NewTaskActivityLabel));
                break;
            case TASK_INFO:
                toolbar.setTitle(getString(R.string.TaskInfoActivityLabel));
                int taskUID = intent.getIntExtra("UID", 0);
                Task task = TaskList.getInstance().findByID(taskUID);
                ((TextView) findViewById(R.id.title_edit_text)).setText(task.getTitle());
                ((TextView) findViewById(R.id.subject_edit_text)).setText(task.getSubject());
                ((TextView) findViewById(R.id.detail_content_edit_text))
                        .setText(task.getDetailContent());
                LocalDateTime deadline = task.getDeadline();
                ((TextView) findViewById(R.id.expire_date))
                        .setText(String.format("%04d-%02d-%02d", deadline.getYear(),
                                deadline.getMonth().getValue(), deadline.getDayOfMonth()));
                ((TextView) findViewById(R.id.expire_time))
                        .setText(String.format("%02d:%02d", deadline.getHour(),
                                deadline.getMinute()));
                ((Spinner) findViewById(R.id.remind_type_spinner))
                        .setSelection(RemindType.getPosition(task.getRemindType()));
                break;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_task, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_add_task) {
            //获取作业信息
            String title = ((TextView)
                    findViewById(R.id.title_edit_text)).getText().toString();
            String subject = ((TextView)
                    findViewById(R.id.subject_edit_text)).getText().toString();
            String detailContent = ((TextView)
                    findViewById(R.id.detail_content_edit_text)).getText().toString();
            String expireDate = ((TextView)
                    findViewById(R.id.expire_date)).getText().toString();
            String expireTime = ((TextView)
                    findViewById(R.id.expire_time)).getText().toString();
            boolean isFinished = ((Switch) findViewById(R.id.finish_swich)).isChecked();
            RemindType remindType = (RemindType) ((Spinner)
                    findViewById(R.id.remind_type_spinner)).getSelectedItem();

            if (expireDate.isEmpty() || expireTime.isEmpty()) {
                Snackbar.make(findViewById(R.id.new_task_toolbar), R.string.no_deadline_warning,
                        Snackbar.LENGTH_LONG).setAction("Action", null).show();
            } else {
                TaskList taskList = TaskList.getInstance();
                if (activityType == NEW_TASK) {
                    Task newTask = new Task(title, subject, detailContent, LocalDate.now(),
                            LocalDateTime.parse(expireDate + "T" + expireTime + ":00"), isFinished);
                    taskList.addNewTask(newTask);
                } else {
                    Task origin = taskList
                            .findByID(getIntent().getIntExtra("UID", 0));
                    origin.setTitle(title);
                    origin.setSubject(subject);
                    origin.setDetailContent(detailContent);
                    origin.setDeadline(
                            LocalDateTime.parse(expireDate + "T" + expireTime + ":00"));
                    origin.setRemindType(remindType);
                    origin.setFinished(isFinished);
                    taskList.removeFromUnfinished(origin.getUID());
                    origin.setLastModify(LocalDateTime.now());
                    new Thread(() ->
                            TaskDatabase.getInstance().taskDAO().update(origin)).start();
                }

                finish();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        parent.getItemAtPosition(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}